package cn.xkai.exercise.b;

import com.google.gson.Gson;

/**
 * @description: 旋转链表
 * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
 * 自己的思路：根据数组下标偏移计算把链表数据根据计数法放到数组中，然后循环链接成新链表
 * 借鉴的思路：把链表闭成环，根据长度计算环断开点
 * @author: kaixiang
 * @date: 2022-07-25
 */
public class Solution96 {
    public ListNode rotateRight(ListNode head, int k) {
        int len = length(head);
        if (len < 2) {
            return head;
        }
        ListNode[] nodes = new ListNode[len];
        k = k > len ? k % len : k;
        int index = 0;
        for (int i = 0; i < len; i++) {
            if (i + k < len) {
                nodes[i + k] = head;
            } else {
                nodes[index++] = head;
            }
            head = head.next;
        }
        for (int i = 0; i < nodes.length - 1; i++) {
            nodes[i].next = nodes[i + 1];
        }
        nodes[len - 1].next = null;
        return nodes[0];
    }

    private int length(ListNode head) {
        int size = 0;
        while (head != null) {
            size++;
            head = head.next;
        }
        return size;
    }

    public ListNode rotateRightRefer(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }
        // 链表长度n
        int n = 1;
        ListNode curr = head;
        while (curr.next != null) {
            n++;
            curr = curr.next;
        }
        // 链表尾节点连接头节点，闭合成环
        curr.next = head;
        // n - k % n是新链表头节点的索引
        // n - k % n - 1是新链表尾节点的索引
        for (int i = 0; i < n - k % n - 1; i++) {
            head = head.next;
        }
        ListNode newHead = head.next;
        // 断开环
        head.next = null;
        return newHead;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5);
        ListNode node4 = new ListNode(4);
        ListNode node3 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        ListNode node1 = new ListNode(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        int k = 6;
        Solution96 solution96 = new Solution96();
        System.out.println(new Gson().toJson(solution96.rotateRight(node1, k)));
    }
}
